import { pageLedger, saveLedger } from "../../../service/api/api-assess-ledger";
import Message from 'tdesign-miniprogram/message/index';
import { pageRecord, searchTreeSource, treeAssessRecordArea, updateRecordState } from "../../../service/api/api-assess-record";
// pages/assess/render/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //用户信息
    currentUser: {},//当前用户
    access: {} as any,// 当前用户权限
    //分页
    hasMoreData: true, // 是否还有更多数据
    pageSize: 8, // 每页数据数量
    currentPage: 1, // 当前页数
    firstReachBottom: 0,//是否第一次触底
    total: 0,//所有数据条数
    //考核数据
    tabList: [],
    stateTabList: [
      {
        state: [1, 3],
        name: "全部"
      }, {
        state: [1],
        name: "申请"
      }, {
        state: [3],
        name: "通过"
      }],//状态列表
    stateValue: 0,//选择的状态的index
    selectStates: [1, 3],//所选择的状态列表
    areaSelectionsList: [],//区域列表
    selectAreaIds: [],//选择的区域id列表
    UnitDrawerVisible: false,//质效考核单位选择抽屉
    viewDrawerAddLedgerVisible: false,//新增考核抽屉
    activeTabKey: '',
    ledgerId: 0,//年度id
    ledgerName: '',//选择的年度
    group1: '',
    group2: '',
    group3: '',
    areaId: [],//单位id
    value: '',//选择的年度的index
    assessList: [],//考核列表
    createdSource: 2,//小程序请求列表
    fabButton: {
      theme: 'light'
    },
    //新增考核
    titleName: '',//标题
    datetimeVisible: false,//开始时间选择器是否显示
    datetime: new Date().getTime(),//选择的时间
    datetimeText: '',//所选择的开始时间
    datetimeEndVisible: false,//开始时间选择器是否显示
    datetimeEnd: new Date().getTime(),//选择的时间
    datetimeEndText: '',//所选择的开始时间
    //通过考核
    viewshowConfirm: false,//通过审核的确认框是否打开
    recordScore: 0,//考核分数最终
    firstColor: 'red',//第一个来源标签的颜色
    swipeData: 0,//滑动的itemid
  },
  //输入标题
  onTitleNameInput(e) {
    this.setData({
      titleName: e.detail.value
    })
  },
  //显示时间选择器
  showPicker(e) {
    this.setData({
      datetimeVisible: true,
    });
  },
  //隐藏时间选择器
  hidePicker() {
    this.setData({
      datetimeVisible: false,
    });
  },
  //显示时间选择器
  showEndPicker(e) {
    if (this.data.datetimeText) {
      this.setData({
        datetimeEndVisible: true,
      });
    } else {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请先选择开始时间',
      });
    }
  },
  //隐藏时间选择器
  hideEndPicker() {
    this.setData({
      datetimeEndVisible: false,
    });
  },
  //判断选择的截止时间是否在当天之前
  onComfirmSelectTime(value) {
    const selectedTime = new Date(value).getTime();
    const startTime = new Date(this.data.datetime).getTime()
    if (selectedTime <= startTime) {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请选择开始时间之后的时间',
      });
      return false; // 阻止选择
    } else {
      return true;
    }
  },
  //确认所选择的时间
  onConfirm(e) {
    const { value } = e.detail;
    // if (!this.onComfirmSelectTime(value)) {
    // } else {
    this.setData({
      datetime: value,
      datetimeText: value,
    });
    this.hidePicker();
    // }
  },
  //确认所选择的时间
  onConfirmEnd(e) {
    const { value } = e.detail;
    if (!this.onComfirmSelectTime(value)) {
    } else {
      this.setData({
        datetimeEnd: value,
        datetimeEndText: value,
      });
      this.hidePicker();
    }
  },
  //提交新增的考核
  onSubmitLedger() {
    if (this.data.name === '') {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请输入标题',
      });
      return false
    }
    if (this.data.datetime === null) {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请选择开始时间',
      });
      return false
    }
    if (this.data.datetimeEnd === null) {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请选择结束时间',
      });
      return false
    }
    getApp().preventActive(async () => {
      const response = await saveLedger({
        dateRange: [this.data.datetime, this.data.datetimeEnd],
        name: this.data.titleName
      });
      if (response.code === 0) {
        Message.success({
          context: this,
          offset: [20, 32],
          duration: 5000,
          content: '创建成功',
        });
        this.onLoadLedgerList();
        this.closeAddLedger()
      }
    })
  },
  //关闭新增考核抽屉
  closeAddLedger() {
    this.setData({
      viewDrawerAddLedgerVisible: false,
      datetimeEndText: '',
      datetime: new Date().getTime(),
      datetimeEnd: new Date().getTime(),
      datetimeText: '',
      titleName: ''
    })
  },
  //输入最终分数
  onFinalScoreInput(e) {
    this.setData({
      recordScore: e.detail.value
    })
  },
  //打开是否通过的确认框
  openConfirm(e) {
    const item = e.currentTarget.dataset.item
    this.setData({
      viewshowConfirm: true,
      swipeData: item
    })
  },
  //点击确认后的弹窗关闭
  closeConfirmDialog() {
    this.setData({
      viewshowConfirm: false,
      recordScore: 0
    })
  },
  //通过此考核
  onSwipePass(e) {
    getApp().preventActive(async () => {
      const response = await updateRecordState({ id: this.data.swipeData.id, finalScore: this.data.recordScore, state: 3 });
      if (response.code === 0) {
        Message.success({
          context: this,
          offset: [20, 32],
          duration: 5000,
          content: '提交成功',
        });
        this.onLoadRecordTable({ current: this.data.currentPage, pageSize: this.data.pageSize, areaId: this.data.areaId, ledgerId: this.data.ledgerId, sourceTopId: this.data.activeTabKey })
      }
    })
  },

  /**
* 预备Tree结构数据
* @param data
*/
  readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = [];
    if (data) {
      data.forEach((val) => {
        if (val.isFolder === 1 && val.children === undefined) {
        } else {
          treeData.push({
            name: val.name,
            id: val.id,
            parentId: val.parentId,
            checkbox: true,
            isFolder: val.isFolder,
            isChildren: val.children === undefined ? 0 : 1,
            children: this.readyTreeData(val.children as AdminOrganizationData.Organization[]),
          });
        }
      });
    }
    return treeData;
  },
  //加载任务列表
  async onLoadLedgerList() {
    const res = await pageLedger({ current: 1, pageSize: 20 })
    if (res.code === 0) {
      this.setData({
        tabList: res.data.data,
        ledgerId: res.data.data[0].id,
        ledgerName: res.data.data[0].name,
        group1: res.data.data[0].group1,
        group2: res.data.data[0].group2,
        group3: res.data.data[0].group3
      })
      this.onLoadRecordTable({ current: this.data.currentPage, pageSize: this.data.pageSize, areaId: this.data.areaId, ledgerId: res.data.data[0].id, sourceTopId: this.data.activeTabKey, states: this.data.selectStates })
    }
  },
  //加载考核列表
  async onLoadRecordTable(params: { areaId: number, sourceTopId: number, ledgerId: number, current: number, pageSize: number, states: any }) {
    wx.showLoading({
      title: '加载中...'
    })
    if (this.data.ledgerId !== 0) {
      const response = await pageRecord({
        createdSource: this.data.createdSource,
        areaIds: params.areaId,
        sourceTopId: params.sourceTopId,
        ledgerId: params.ledgerId,
        current: params.current,
        pageSize: params.pageSize,
        states: params.states
      })
      const hasMoreData = response.data.total >= params.pageSize * params.current;
      const list = response.data.data
      if (response.code === 0) {
        this.setData({
          assessList: list,
          total: response.data.total,
          hasMoreData
        })
      }
      wx.hideLoading()
    }

  },
  //选择单位、年度
  onTabsClick(e) {
    this.onOpenUnitDrawer()
  },
  //选择
  onTabsChange(e) {
    this.setData({
      activeTabKey: e.detail.value
    })
    this.onLoadRecordTable({ current: this.data.currentPage, pageSize: this.data.pageSize, areaId: this.data.areaId, ledgerId: this.data.ledgerId, sourceTopId: this.data.activeTabKey })
  },
  //选择年度
  onLedgerTabsChange(e) {
    this.setData({
      ledgerId: e.detail.value
    })
  },
  //新增考核
  AddLedger() {
    this.setData({
      viewDrawerAddLedgerVisible: true
    })
  },
  //加载区域Tree结构数据
  async loadtTreeAssessRecordArea() {
    const response = await treeAssessRecordArea({ ledgerId: this.data.ledgerId, sourceTopId: this.data.activeTabKey, states: this.data.selectStates })
    if (response.code === 0) {
      this.setData({
        areaSelectionsList: this.readyTreeData(response.data)
      })
    }
  },
  onClickDrawerAreaItem(e) {
    const { idList } = e.detail;
    this.setData({
      areaId: idList,
    })
    this.onLoadRecordTable({ current: this.data.currentPage, pageSize: this.data.pageSize, areaId: idList, ledgerId: this.data.ledgerId, sourceTopId: this.data.activeTabKey })
  },
  //打开详细信息抽屉
  onOpenUnitDrawer() {
    this.setData({
      UnitDrawerVisible: true
    })
    this.loadtTreeAssessRecordArea()
  },
  //选择年度改变
  onChangeLedgerId(e) {
    let selectId = this.data.tabList[e.detail.value].id
    let selectName = this.data.tabList[e.detail.value].name
    let group1 = this.data.tabList[e.detail.value].group1
    let group2 = this.data.tabList[e.detail.value].group2
    let group3 = this.data.tabList[e.detail.value].group3
    this.setData({ value: e.detail.value, ledgerId: selectId, ledgerName: selectName, group1, group2, group3 });
    this.onLoadRecordTable({ current: this.data.currentPage, pageSize: this.data.pageSize, areaId: this.data.areaId, ledgerId: selectId, sourceTopId: this.data.activeTabKey })
    this.loadtTreeAssessRecordArea()
  },
  //选择年度改变
  onChangeState(e) {
    let states = this.data.stateTabList[e.detail.value].state
    this.setData({ stateValue: e.detail.value, selectStates: states, areaId: [] });
    this.loadtTreeAssessRecordArea()
    this.onLoadRecordTable({ current: this.data.currentPage, pageSize: this.data.pageSize, areaId: this.data.areaId, ledgerId: this.data.ledgerId, sourceTopId: this.data.activeTabKey, states })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    const { globalData: { access, currentUser } } = getApp();
    this.setData({
      access,
      currentUser
    })
    // Message.info({
    //   context: this,
    //   offset: [20, 32],
    //   duration: 5000,
    //   content: '2024年第一季度全媒体质效考核任务入口已经开启，请各位用户按要求填写',
    //   closeBtn: true,
    // });
    this.onLoadLedgerList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.onLoadRecordTable({ current: this.data.currentPage, pageSize: this.data.pageSize, areaId: this.data.areaId, ledgerId: this.data.ledgerId, sourceTopId: this.data.activeTabKey })
    // if (this.data.access.instructConfigManage) {
    //   let page = wx.getStorageSync('render-page');
    //   console.log('=======page=====', page);
    //   if (page == 'detail') {
    //     // this.setData({
    //     //   [`instructList[${index}].beforNow`]: '哈哈哈哈',
    //     // })
    //   } else if (page == "create") {
    //     let add = wx.getStorageSync('instruct-create-add')
    //     if (add) {
    //       this.onLoadLedgerList();
    //     } else {
    //     }
    //   } else if (page == "address") {
    //   } else {

    //   }
    // } else {
    //   Message.warning({
    //     context: this,
    //     offset: [20, 32],
    //     duration: 5000,
    //     content: '暂无权限',
    //   });
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },
  async onRefresh() {
    //导航条加载动画
    wx.showNavigationBarLoading();
    //停止下拉刷新
    const response = await pageRecord({ current: 1, pageSize: 8, areaId: this.data.areaId, ledgerId: this.data.ledgerId, sourceTopId: this.data.activeTabKey });
    if (response.code === 0) {
      const hasMoreData = response.data.total >= 8;
      const list = response.data.data
      // list.forEach(item => {
      //   item.beforNow = calculateDaysAgo(item.createdTime)
      // })
      this.setData({
        assessList: list,
        hasMoreData,
        currentPage: 1,
        total: response.data.total,
        pageSize: 8
      })
    }
    setTimeout(() => {
      wx.stopPullDownRefresh();
      wx.hideNavigationBarLoading();
    }, 1000);
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.setData({
      firstReachBottom: this.data.firstReachBottom + 1
    })
    if (this.data.total > this.data.pageSize) {
      wx.showLoading({
        title: '加载中...'
      })
      if (this.data.hasMoreData) {
        const nextPage = this.data.currentPage + 1;
        this.setData({
          currentPage: nextPage
        })
        this.onLoadRecordTable({ current: this.data.currentPage, pageSize: this.data.pageSize, areaId: this.data.areaId, ledgerId: this.data.ledgerId, sourceTopId: this.data.activeTabKey })
        wx.hideLoading()
      } else {
        if (this.data.firstReachBottom === this.data.currentPage) {
          wx.showToast({
            title: '已加载完成'
          })
        }
        wx.hideLoading()
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})